package msb.class01;

import org.junit.Assert;
import org.junit.Test;
import common.util.ArrayUtil;

import java.util.Arrays;
import java.util.Random;

/**
 * 有序数组中找到>=num最左的位置
 */
public class Code05_BSNearLeft {

    public int existsSimple(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= num) {
                return i;
            }
        }
        return -1;
    }

    public int exists(int[] arr, int num) {
        int L = 0;
        int R = arr.length - 1;
        int mid;
        int index = -1;
        while (L <= R) {
            mid = L + ((R - L) >> 1);
            if (arr[mid] < num) {
                L = mid + 1;
            } else {
                index = mid;
                R = mid - 1;
            }
        }
//        System.out.println("arr:" + Arrays.toString(arr));
//        System.out.println("num:" + num);
//        System.out.println("index:" + index);
        return index;
    }

    @Test
    public void check() {
        int count = 10000;
        int fail = 0;
        for (int i = 0; i < count; i++) {
            Random random = new Random();
            int num = random.nextInt(100);
            int[] arr = ArrayUtil.instant(100, 100);
            Arrays.sort(arr);
            int exists = exists(arr, num);
            int existsSimple = existsSimple(arr, num);
            if (exists != existsSimple) {
                fail++;
                System.out.println("arr:" + Arrays.toString(arr));
                System.out.println("num:" + num);
                System.out.println("exists:" + exists + ",checkExists:" + existsSimple);
            }
        }
        Assert.assertEquals(0, fail);
    }

}
